/**
 * Application Async Task.
 *
 * Released under Apache License, Version 2.0.
 */

package bsp.eclair.simplelinechart;

import android.os.AsyncTask;

public class ApplicationAsyncTask extends AsyncTask <Long, Long, Long>
{
	protected ActivityMain mParentActivity;
	protected boolean mRun;
	protected long mCounter;
 
	public ApplicationAsyncTask(ActivityMain parentActivity)
	{
		mParentActivity = parentActivity;
		mRun = false;
	}
 
	public void setRunning(boolean flag)
	{
		mRun = flag;
	}
	
	// can use UI thread here
	protected void onPreExecute()
	{
		mCounter = 0;
	}
	
	// automatically done on worker thread (separate from UI thread)
	@Override
	protected Long doInBackground(final Long... args)
	{
		while ( mRun ) {
			mParentActivity.addData();
			
			publishProgress(mCounter);
			
			sleepSomeTimeConsumeInterruptedException(5000);
			
			mCounter++;
		}
		
		return Long.valueOf(mCounter);
	}
	
	// periodic updates - it is OK to change UI
	@Override
	protected void onProgressUpdate(Long... value)
	{
		super.onProgressUpdate(value);
		
		mParentActivity.refresh();
	}
	
	// End - can use UI thread here
	protected void onPostExecute(final Long result)
	{
	}
	
	public static void sleepSomeTimeConsumeInterruptedException(int duration)
	{
		try {
			Thread.sleep(duration);
		} catch ( InterruptedException ex ) {
			// nothing here by design
		}
	}
}

/* end */
